package com.hserver.docker.controller;

import cn.hserver.plugin.web.annotation.Controller;
import cn.hserver.plugin.web.annotation.GET;
import cn.hserver.plugin.web.annotation.RequestMapping;
import cn.hserver.plugin.web.annotation.RequestMethod;
import cn.hserver.plugin.web.interfaces.HttpRequest;
import cn.hserver.plugin.web.interfaces.HttpResponse;
import com.hserver.docker.config.ConstConfig;
import com.hserver.docker.service.DeployService;
import com.hserver.docker.service.DockerService;
import com.hserver.docker.service.RecordService;
import cn.hserver.core.ioc.annotation.*;
import cn.hserver.core.queue.HServerQueue;
import cn.hserver.core.server.util.JsonResult;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 线上环境的后台服务自动化部署
 */
@Controller("/deploy/")
public class DeployController {

    @Autowired
    private DeployService deployService;

    @Autowired
    private RecordService recordService;

    @Autowired
    private DockerService dockerService;

    /**
     * 部署
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "deploy/{uuid}", method = {RequestMethod.POST, RequestMethod.GET, RequestMethod.PUT})
    public JsonResult deploy(HttpRequest request) throws IOException {
        String uuid = request.query("uuid");
        if (uuid != null && deployService.checkSource(request, uuid)) {
            String id = UUID.randomUUID().toString();
            String desc = request.getRawData();
            if (desc == null || desc.trim().length() == 0) {
                desc = "手动部署";
            }
            HServerQueue.sendQueue("deploy", uuid, id, desc);
            return JsonResult.ok().put("recordId", id);
        } else {
            return JsonResult.error("部署条件不满足");
        }
    }


    /**
     * 重启
     * @param uuid
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "restart", method = {RequestMethod.POST})
    public JsonResult restart(String uuid) throws IOException {
        dockerService.runContainer(uuid);
        return JsonResult.ok();
    }

    /**
     * 停止容器
     * @param uuid
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "stop", method = {RequestMethod.POST})
    public JsonResult stop(String uuid) throws IOException {
        dockerService.stopContainer(uuid);
        return JsonResult.ok();
    }


    /**
     * 删除容器
     * @param uuid
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "remove", method = {RequestMethod.POST})
    public JsonResult remove(String uuid) throws IOException {
        dockerService.stopContainer(uuid);
        dockerService.removeContainer(uuid);
        return JsonResult.ok();
    }

    /**
     * 回滚指定的ID部署
     *
     * @param uuid
     * @param recordId
     * @throws IOException
     */
    @GET(value = "rollback/{uuid}/{recordId}")
    public JsonResult rollback(String uuid, String recordId) throws IOException {
        try {
            dockerService.runRollBackContainer(uuid, recordId);
        } catch (Exception e) {
            return JsonResult.error();
        }
        return JsonResult.ok();
    }


    /**
     * 查询状态
     * @param uuid
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "status", method = {RequestMethod.POST})
    public JsonResult status(String uuid) throws IOException {
        return JsonResult.ok().put("data", dockerService.infoContainer(uuid));
    }


    /**
     * 下载日志
     */
    @RequestMapping(value = "downloadLog/{recordId}", method = RequestMethod.GET)
    public void downloadLog(String recordId, HttpResponse response) {
        if (recordId != null) {
            response.setDownloadFile(new File(ConstConfig.LOG_PATH + recordId + ".log"));
        } else {
            response.sendText("下载失败");
        }
    }

    /**
     * 删除镜像
     */
    @RequestMapping(value = "remove/{recordId}", method = RequestMethod.GET)
    public void remove(String recordId, HttpResponse response) {
        try {
            //删除镜像
            try {
                dockerService.removeImage(recordId);
            } catch (Exception e) {
                response.redirect("/");
            }
            //删除日志
            new File(ConstConfig.LOG_PATH + recordId + ".log").delete();
            //删除record
            recordService.removeId(recordId);
        } catch (Exception e) {
            response.redirect("/");
        }
    }

}
